import React, { Component } from 'react'
import {Switch, Route, Redirect} from 'react-router-dom'
export default class RouterView extends Component {
    // 设置默认的props方法
    static defaultProps = {
        routes: [],
        matchPath: ''
    }

    // 导航守卫
    beforeEnter = (item, matchPath, index) => {
        // 获取token 证明是否登陆
        const token = localStorage.getItem('token');

        const Com = item.component;

        // localStorage.setItem('token', '12312312');
        // localStorage.clear();
        // localStorage.removeItem('')
        if(token) {
            return <Route key={index} path={matchPath + item.path} render={(props) => <Com {...props} routes={item.children}></Com>}></Route>
        } else {
            return <Redirect exact to='/login'></Redirect>
        }
    }
    render() {
        let {routes, matchPath} = this.props
        return (
            <Switch>
                {
                    routes ? routes.map((item, index) => {
                        // return <Route path={item.path} component={item.component}></Route>
                        const Com = item.component;
                        // 重定向
                        if(item.from) {
                            return <Redirect key={-1} exact from={matchPath + item.from} to={item.to}></Redirect>
                        }
                        return <Route key={index} path={matchPath + item.path} render={(props) => item.isLogin ? this.beforeEnter(item, matchPath, index) : <Com {...props} routes={item.children}></Com>}></Route>
                    }) : null
                }
            </Switch>
        )
    }
}


// import React from 'react'

// export default function RouterView(props) {
//     return (
//         <div>
//             {
//                 props.routes
//             }
//         </div>
//     )
// }
